package top.xia17.plugins.fast.common.database.jpa.custom;

import cn.hutool.core.lang.Snowflake;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

/**
 * JPA 雪花主键生成器
 * @author xia17
 * @date 2020/7/22 15:52
 */
public class SnowFlakeIdGenerator implements IdentifierGenerator {

    private final Snowflake snowflake;

    public SnowFlakeIdGenerator() {
        this.snowflake = new Snowflake(1,1);
    }

    public SnowFlakeIdGenerator(long workerId, long datacenterId) {
        this.snowflake = new Snowflake(workerId,datacenterId);
    }

    public SnowFlakeIdGenerator(Snowflake snowflake) {
        this.snowflake = snowflake;
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        return snowflake.nextId();
    }
}
